const mqtt = require('mqtt')
const mqttClient = mqtt.connect('mqtt://192.168.1.106:1883')
// const mqttTopic = { 'tx': 0, 'rx': 0 }
const mqttTopic = 'fsc/#'
// server = require('http').createServer(app),
// io = require('socket.io').listen(server);

var streamInterval;
var msFrequency = 20;

actions = [
    {
        name:'智能场景1',
        condition: 'and',
        if: {
                topic:'fsc/rx',
                message:{
                    aswcode: '100',
                    aswmsg: '1',
                }
            },
        do: {
                topic:'fsc/tx',
                message:{
                    code: '200',
                    msg: '0',
                }
            },
    }
]

/* 
Subscribe (listen) to MQTT topic and start publishing
simulated data after successful MQTT connection 
*/
mqttClient.on('connect', () => {
    console.log('Mqtt connected.')
    mqttClient.subscribe(mqttTopic); //subscribe
    // mqttClient.subscribe({'topic': 0, 'topic2': 1})
    // startStreamSimulation(); //publish
})

mqttClient.on('offline', () => {
    console.log('Mqtt offline.')
    mqttClient.unsubscribe(mqttTopic);
    clearInterval(streamInterval);
})

/* 
Message event fires, when new messages
arrive on the subscribed topic
*/
mqttClient.on('message', function (topic, message) {
    console.log('Received: ' + message.toString() + ' from topic: ' + topic.toString()); 
    const msg = JSON.parse(message)
    for(var i=0;i<actions.length;i++) {
        const act = actions[i]
        if (act.if.topic === topic){
            const act_if = act.if.message
            if(act_if.aswcode === msg.aswcode & act_if.aswmsg === msg.aswmsg) {
                console.log(act.name)
                console.log('满足条件')
                mqttClient.publish(act.do.topic, JSON.stringify(act.do.message));
                break
            }
        }
    }
    // let parsedMessage = JSON.parse(message);
    // io.emit('voltageData', parsedMessage);
})

/* 
Function that publishes simulated data to the MQTT broker every ≈20ms
*/
function startStreamSimulation() {
    
    var v1 = 0,
        v2 = 0,
        v3 = 0;

    streamInterval = setInterval(function () {

        /* Prepare random data */
        v1 = returnRandomFloat(231, 231.1);
        v2 = returnRandomFloat(235, 235.3);
        v3 = returnRandomFloat(238.7, 239.3);

        /* Publish random data to the corresponding MQTT topic as a JSON string  */
        mqttClient.publish(mqttTopic, JSON.stringify({
            'v1': v1,
            'v2': v2,
            'v3': v3
        }));


    }, msFrequency);
}

function returnRandomFloat(min, max) {
    return (Math.random() * (max - min) + min).toFixed(2);
}

// io.on('connection', (client) => {
//     console.log("Socket connected.")
// })

module.exports = mqtt;

